package com.example.demo.service.impl;

import com.example.demo.common.code.ErrorCode;
import com.example.demo.common.constant.SysConstant;
import com.example.demo.common.exception.LoginException;
import com.example.demo.config.SSOConfig;
import com.example.demo.dao.MpSysUserDao;
import com.example.demo.model.SysUserModel;
import com.example.demo.model.base.SysUserToken;
import com.example.demo.model.enums.RespEnum;
import com.example.demo.model.req.SysUserLoginReq;
import com.example.demo.model.req.SysUserRegisterReq;
import com.example.demo.pojo.MpSysUserDO;
import com.example.demo.service.ITokenService;
import com.example.demo.service.IUserService;
import com.example.demo.utils.CacheUtil;
import com.example.demo.utils.CookieUtil;
import com.example.demo.utils.RespBean;
import com.example.demo.utils.TinyUUIDGenerate;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class IUserServiceImpl implements IUserService {
    @Autowired
    MpSysUserDao mpSysUserDao;
    @Autowired
    SSOConfig SSOConfig;
    @Autowired
    ITokenService iTokenService;


    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysUserToken login(SysUserLoginReq sysUserLoginReq, HttpServletRequest request, HttpServletResponse response) {
        String sysUserName = sysUserLoginReq.getSysUserName();
        MpSysUserDO userDO = getByUserName(sysUserName);
        String sysUserId = userDO.getSysUserId();
        String realName = userDO.getRealName();

        String userPassKey = CacheUtil.LimitLoginKey(sysUserId);
        String cacheNums = stringRedisTemplate.opsForValue().get(userPassKey);
        if(StringUtils.equals(SSOConfig.getMaxInvalidNums().toString(),cacheNums))
        {
            throw LoginException.build(ErrorCode.Lock_User);
        }
        if(!StringUtils.equals(userDO.getPassword(),sysUserLoginReq.getPassword()))
        {
            if(StringUtils.equals(cacheNums,"4"))
            {
                stringRedisTemplate.opsForValue().set(userPassKey,"5", 30l,TimeUnit.MINUTES);
            }else if(StringUtils.equals(cacheNums,"null")){
                stringRedisTemplate.opsForValue().set(userPassKey,"0");
            }else {
                stringRedisTemplate.opsForValue().increment(userPassKey,1l);
            }
            throw LoginException.build(ErrorCode.INVALID_USERNAME_PASSWORD);
        }
        if(userDO.getIsEnable()!=1)
        {
            throw LoginException.build(ErrorCode.USER_IS_ENABLE);
        }
        SysUserModel userModel = new SysUserModel(sysUserId,sysUserName,realName);
        SysUserToken sysUserToken = iTokenService.createToken(userModel);
        CookieUtil.addCookie(SysConstant.TOKENKEY,sysUserToken.getToken(),"/",request,response);


        return sysUserToken;
    }

    @Override
    public MpSysUserDO getByUserName(String sysUserName) {
        MpSysUserDO mpSysUserDO = mpSysUserDao.selectByUserName(sysUserName);
        if(ObjectUtils.equals(null,mpSysUserDO)){
            throw LoginException.build(ErrorCode.INVALID_USERNAME_PASSWORD);
        }
        return mpSysUserDO;
    }

    @Transactional
    @Override
    public RespBean register(SysUserRegisterReq sysUserRegisterReq, HttpServletRequest request, HttpServletResponse response) {
        String sysUserName = sysUserRegisterReq.getSysUserName();
        MpSysUserDO userDO = new MpSysUserDO();
        userDO.setSysUserName(sysUserName);
        MpSysUserDO existUserDO = mpSysUserDao.selectByUserName(sysUserName);
        if(null!=existUserDO){
            return RespBean.error(RespEnum.USEREXIST);
        }
        userDO.setPassword(sysUserRegisterReq.getPassword());
        userDO.setCreateTime(new Date());

        userDO.setCreateBy(sysUserRegisterReq.getSysUserName());
        userDO.setIsEnable(1);
        userDO.setIsDeleted(0);
        userDO.setVersion(1);
        userDO.setGender(Integer.valueOf(sysUserRegisterReq.getSex()));
        userDO.setSysUserId(TinyUUIDGenerate.generate());
        mpSysUserDao.insert(userDO);
        return RespBean.success(userDO);
    }

    @Override
    public RespBean showUser() {
        List<MpSysUserDO> mpSysUserDOS = mpSysUserDao.select20User();
        return RespBean.success(mpSysUserDOS);
    }
}
